/***********************************************************************************************************************
**	filename: tick.c
**	date: 2013-07-16
***********************************************************************************************************************/

#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "dbg.h"
#include "tick.h"

static pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER;

Tick_DT tick_get(void)
{
	struct timeval timeVal;
	pthread_mutex_lock(&Mutex);
	gettimeofday(&timeVal, 0);
	pthread_mutex_unlock(&Mutex);
#if 1	// changed by niyh 20210602
	return (timeVal.tv_sec*1000 + timeVal.tv_usec/1000);
#else
	Tick_DT timestamp = timeVal.tv_sec - 8 * 60 * 60;
	timestamp *= 1000;
	timestamp += timeVal.tv_usec/1000;
	return timestamp;
#endif
}

inline Tick_DT tick_cmp(Tick_DT start, Tick_DT end)
{
	return end-start;
}

bool tick_timeout(Tick_DT start, Tick_DT timeout)
{
	return ((Tick_DT)tick_cmp(start, tick_get())>timeout);
}

void tick_delay(Tick_DT tick)
{
	usleep(tick*1000);
}

void getUuid(char *buffer, int len)
{
    time_t t;
    /* 初始化随机数发生器 */
    srand((unsigned) time(&t));

    char temp[3];
    for(int i = 0; i < len; i++) {
        uint8_t id = rand() % 16;
        sprintf(temp, "%02x", id);
        memcpy(buffer + i * 2, temp, 2);
    }

    buffer[len * 2] = '\0';
}

/***********************************************************************************************************************
**	endline
***********************************************************************************************************************/
